/**
 * Created by trisatria on 2/17/14.
 */
var _host = "http://minimall.vn/api/";
var _host_img = "http://minimall.vn";
var page = 1;
var _topic_type = '';
var _topic_loc = '';
var _topic_cat = '';
var _url = '';
var _topic_brand_new = '';
var user_id = '';
var activePage;
var product_name;
var select_cat;
var select_loc;
var select_type;
var j_user;
var app_version = 1;
function check_version(){
    $.ajax({
        url : _host + 'appversion',
        type: 'GET',
        async: false
    }).done(function(data){
        var ver = $.parseJSON(data);
        if( app_version < ver[0]['version'] ){
            //$("#index #popupUpdate").popup("open");
            $.mobile.changePage('update.html', {  role: "page", reverse: true } );

        }
    });
}

function init_search(){
    product_name = '';
    select_cat = '';
    select_loc = '';
    select_type = '';
}
//check login
function checklogin() {
    var activePage = $.mobile.activePage[0].id;
    var info_user = $.session.get("logged");
    if (typeof  info_user != "undefined" && info_user != null) {
        console.log(j_user);
        //alert('logged');
        $("#" + activePage + " #logged").show();
        $("#" + activePage + " .login_form").hide();
        j_user = $.parseJSON(info_user);
        user_id = j_user['id'];

        var avatar = _host_img+'/'+j_user['avatar'];
        if(j_user['avatar'].search(/facebook/) != -1){
            var avatar = j_user['avatar'];
        }
        $(".profile_img").attr('src', avatar);

        $(" .profile_email").text(j_user['email']);
        $(" .profile_name").text(j_user['name']);
        $("#" + activePage + " #addproduct").attr('href', 'addproduct.html');
    }
    else{

        //alert('not logged');
        $("#" + activePage + " #logged").hide();
        $("#" + activePage + " .login_form").show();
        $("#" + activePage + " #addproduct").attr('href', 'addproductnotlogged.html');
       // $.mobile.changePage('index.html', {  role: "page", reverse: true } );
    }

    //if not logged
}
//get categories, location, type
function _init() {
    openFB.init({appId: '345700865584560'});
    //check_version();
    $('#alert-sucess').hide();
    //if store
    var data_init = $.cookie("init");
    if (typeof  data_init != "undefined") {
        var jdata = $.parseJSON(data_init);
        _topic_type = jdata['type'];
        _topic_loc = jdata['loc'];
        _topic_cat = jdata['cat'];
    } else {
        //if not store
        $.ajax({
            url: _host + 'index',
            type: 'GET',
            async: false,
            success: function (data) {
                console.log(data);
                $.cookie("init", data);
                var jdata = $.parseJSON(data);
                _topic_type = jdata['type'];
                _topic_loc = jdata['loc'];
                _topic_cat = jdata['cat'];

            }
        });
    }

    $(document).on('swiperight', '.wipe_element_right', function () {
        var activePage = $.mobile.activePage[0].id;
        $("#" + activePage + " #mypanel").panel('open');
        $("#" + activePage + " #mypanel_myproduct").panel('open');
    });
    $(document).on('swipeleft', ' .wipe_element_right', function () {
        var activePage = $.mobile.activePage[0].id;
        $("#" + activePage + " #mypanel_right").panel('open');
    })
    $(document).on('click', '#btn_logout', function () {
        var activePage = $.mobile.activePage[0].id;
        $("#" + activePage + " #logged").hide();
        $("#" + activePage + " .login_form").show();
        $.session.remove('logged');
        checklogin();
        return false;
    })
}
function render(data, div) {
   // console.log(data);
    var content_cat = '';
    if(data['tocatid']!= null && data['tocatid'] != ''){
        content_cat = _topic_cat[parseInt(data['tocatid']) - 1]['title'];
    }
    var content = ' <li class="ui-li-has-thumb"><a href="productdetail.html?product_id=' + data['topi'] + '" data-transition="slide" class="ui-btn"><img style="top:23px" src="' +_host_img+'/'+ data['images'] + '"><h2>' + data['title'] + '</h2><p>' + _topic_type[data['topic_type']] + ' :: ' + _topic_loc[data['topic_location']] + ':: ' + content_cat + '</p>';
    if (data['show_price'] == 1) {
        content += '<p class="price">' + data['price'] + 'VNĐ </p>';
    }
    else {
        content += '<p>Liên Hệ</p>';
    }
    content += '<p>'+ data['create_date']+' <b> '+ $.timeago(data['create_date'])+'</b></p></a></li>';
    //$('#index p.price').formatCurrency();
    $(div).append(content);
    $('#index .price').formatCurrency($.formatCurrency.regions['vi-VN']);
}
$(document).ready(function () {
    page = 1;
    _url = _host + 'topic';
    checklogin();
    _init();
    //load more product
    $('#load_more').click(function () {
        $.mobile.loading("show");
        page = parseInt(page) + 1;
        $.ajax({
            url: _host + 'topic',
            type: 'GET',
            data: {title: product_name, cat: select_cat, loc: select_loc, type: select_type, page: page}

        }).done(function (data) {
            var jdata = $.parseJSON(data);
            console.log(jdata);
            for (var i = 0; i < jdata.length; i = parseInt(i) + 1) {
                render(jdata[i], '#ajax_table');
            }
            $.mobile.loading("hide");
        });
    })
    //end load more product

    //allproduct
    $("#allproduct").click(function () {
        _url = _host + 'topic'
        page = 1;
        $('#ajax_table').empty();
        $.ajax({
            url: _url,
            type: 'GET',
            data: {page: page }
        }).done(function (data) {
            var jdata = $.parseJSON(data);
            console.log(jdata);
            for (var i = 0; i < jdata.length; i = parseInt(i) + 1) {
                render(jdata[i], '#ajax_table');
            }
        });
        return false;
    })
    //end all product

    //init location
    for (var i = 0; i < _topic_loc.length; i = parseInt(i) + 1) {
        var content = '<option value="' + i + '" >' + _topic_loc[i] + '</option>';
        $('.select_loc').append(content);

    }
    //init cat
    for (var i = 0; i < _topic_cat.length; i = parseInt(i) + 1) {

        var content = '<option value="' + _topic_cat[i]['id'] + '" >' + _topic_cat[i]['title'] + '</option>';
        $('.select_cat').append(content);
    }
})
$(document).on('pageshow', '#index', function (event) {
    init_search();
    checklogin();
    $.mobile.loading("show");
    //get products
    page = 1;
    $('#ajax_table').empty();
    $.ajax({
        url: _host + 'topic',
        type: 'GET',
        data: {page: page }
    }).done(function (data) {
        var jdata = $.parseJSON(data);
        for (var i = 0; i < jdata.length; i = parseInt(i) + 1) {
            render(jdata[i], '#ajax_table');
        }
        $.mobile.loading("hide");
    })

    //end get products
});
$(document).on('click', '.submit-ajax-register', function () {

    $.mobile.loading('show');
    var pass = true;
    var _url = $("#signupsss").attr('action');
    var fiel = $(".ui-field-contain");
    var formname = $("#signupsss").attr('name');
    var formData = $("#signupsss").serialize();
    $(fiel).find("label span").each(function () {
        if ($(this).html() == '*') {
            if ($(this).parent().parent().find('input').val() == '') {
                if (pass) pass = false;
                $(this).parent().parent().find('input').css("border", "1px solid red");
                $(this).parent().parent().find('input').attr('placeholder', 'Vui lòng điền vào trường này');
            }
        }

    });
    $.mobile.loading('hide');
    if (!pass) return false;
    else {

        $.ajax({
            url: _host + _url,
            type: 'POST',
            data: formData,
            dataType: 'html',
            beforeSend: function () {
                $.mobile.loading('show');
            },
            success: function (response) {
                // response = JSON.parse(response);
                console.log(response);
                $.removeCookie("logged");
                $.cookie("logged", response);
                $.mobile.loading('hide');
                alert('Đăng ký thành công');
                $.mobile.loading('hide');
                $.resetForm(formname);

            },
            error: function () {
                // jerror('Request timeout');
                /// $(".overlay-loading").fadeOut(1000);
            }
        });
        $.mobile.loading('hide');
        return false;

    }
    return false;
});
/*submit ajax validation*/
$(document).on('click', '.submit-ajax', function () {

    $.mobile.loading('show');
    var ui_content = $(".ui-content");
    var form = $(ui_content).find("form.ajax-form");
    var pass = true;
    var _url = $(form).attr('action');
    var fiel = $(".ui-field-contain");
    var formname = $(form).attr('name');
    var formData = $(form).serialize();
    var reset = $(form).attr('reset');
    var object = $(form).attr('object');
    $(fiel).find("label span").each(function () {
        if ($(this).html() == '*') {
            if ($(this).parent().parent().find('input').val() == '') {
                if (pass) pass = false;
                $(this).parent().parent().find('input').css("border", "1px solid red");
                $(this).parent().parent().find('input').attr('placeholder', 'Vui lòng điền vào trường này');
            }
        }

    });
    $.mobile.loading('hide');
    if (!pass) return false;
    else {

        $.ajax({
            url: _host + _url,
            type: 'POST',
            data: formData,
            dataType: 'html',
            beforeSend: function () {
                $.mobile.loading('show');
            },
            success: function (response) {
                if (object == 'true') {
                    $.removeCookie("logged");
                    $.cookie("logged", response);
                } else {
                    response = JSON.parse(response);
                    console.log(response);
                    $.removeCookie("logged");
                    $.cookie("logged", response.data);
                    alert(response.message);
                }
                $.mobile.loading('hide');
                if (reset == 'true') {
                    $.resetForm(formname);
                }

            },
            error: function () {
                alert('Request timeout!');
                // jerror('Request timeout');
                /// $(".overlay-loading").fadeOut(1000);
            }
        });
        $.mobile.loading('hide');
        return false;

    }
    return false;
});
$.resetForm = function (formName) {
    $("form[name=" + formName + "] input:not(input[type=hidden], input[type=submit])").each(function () {
        $(this).val('');
    });
    $("form[name=" + formName + "] textarea").each(function () {
        $(this).val('');
    });
}
$(window).on("scrollstop", function (event) {
    //alert('scrolltop: '+ $(window).scrollTop() + 'dcHeght: ' + $(document).height() + ' windowHeight ' + $(window).height());
    if ($(document).height() > $(window).height()) {
        if (($(window).scrollTop() / ($(document).height() - $(window).height())) >= 0.5) {
            var activePage = $.mobile.activePage[0].id;
            //alert(activePage)
            if (activePage == 'index') {
                //$.mobile.loading("show");
                page = parseInt(page) + 1;
                $.ajax({
                    url: _host + 'topic',
                    type: 'GET',
                    data: {title: product_name, cat: select_cat, loc: select_loc, type: select_type, page: page}

                }).done(function (data) {
                    var jdata = $.parseJSON(data);
                    console.log(jdata);
                    if(jdata.length!=0){
                        for (var i = 0; i < jdata.length; i = parseInt(i) + 1) {
                            render(jdata[i], '#ajax_table');
                        }
                    }else{
                        $('.no-topic-info').remove();
                         $('#ajax_table').append('<li class="ui-li-has-thumb no-topic-info" style="padding-top: 15px; padding-bottom: 15px;">Không Còn Tin Nào</li>');
                    }
                    //$.mobile.loading("hide");
                });
            }
        }
    }
})

$(document).on('click','#btn_update', function(){
    check_version();
})

//footer menu
$(document).on('click','#footer_refresh',function(){
    location.reload();
});

$(document).on('click','#footer_quit',function(){
    navigator.app.exitApp();
});



